from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, Text
from sqlalchemy.orm import relationship
from app.extensions import db


class User(db.Model):
    __tablename__ = 'users'
    
    id = Column(Integer, primary_key=True)
    openid = Column(String(100), unique=True, nullable=False)
    nickname = Column(String(50))
    avatar_url = Column(String(255))
    phone = Column(String(20))
    password = Column(String(64))
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
    
    # 关联关系
    treatment_records = relationship('TreatmentRecord', backref='user', lazy='dynamic')
    treatment_templates = relationship('TreatmentTemplate', backref='user', lazy='dynamic')
    
    def to_dict(self):
        return {
            'id': self.id,
            'openid': self.openid,
            'nickname': self.nickname,
            'avatar_url': self.avatar_url,
            'phone': self.phone,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'treatment_count': self.treatment_records.count()
        }

    def check_password(self, password):
        if self.password == password:
            return True
        return False
    
    def get_statistics(self):
        """获取用户治疗统计"""
        records = self.treatment_records.all()
        total_treatments = len(records)
        completed_treatments = len([r for r in records if r.status == 'completed'])
        
        return {
            'total_treatments': total_treatments,
            'completed_treatments': completed_treatments,
            'completion_rate': (completed_treatments / total_treatments * 100) if total_treatments > 0 else 0,
            'favorite_mode': self._get_favorite_mode(records),
            'avg_intensity': self._get_avg_intensity(records),
            'total_duration': sum([r.treatment_duration or 0 for r in records])
        }
    
    def _get_favorite_mode(self, records):
        """获取最常用的治疗模式"""
        modes = {}
        for record in records:
            mode = record.treatment_mode
            modes[mode] = modes.get(mode, 0) + 1
        return max(modes.items(), key=lambda x: x[1])[0] if modes else None
    
    def _get_avg_intensity(self, records):
        """获取平均治疗强度"""
        intensities = [r.current_intensity for r in records if r.current_intensity]
        return sum(intensities) / len(intensities) if intensities else 0